<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 4/5/2019
 * Time: 10:16 AM
 */

namespace p5\v2\db;


use p5\objects\ArrayUtils;
use p5\objects\SqlMaker;

class SqlHelper
{

    public static function add(&$sql, $column, $operator, $value)
    {
        if (empty($value)) {
            return;
        }
        $sql .= " and $column $operator $value ";
    }

    public static function addStringIn(&$sql, $column, $value)
    {
        if (empty($value)) {
            return;
        }
        if (is_array($value) && count($value) === 0) {
            return;
        }
        $value = ArrayUtils::forceToArray($value);
        $string = "'" . implode("','", $value) . "'";
        $sql .= " and $column in ($string) ";
    }

    public static function addIn(&$sql, $column, $value)
    {
        if (empty($value)) {
            return;
        }
        if (is_array($value) && count($value) === 0) {
            return;
        }
        $value = ArrayUtils::forceToArray($value);
        $string = implode(",", $value);
        $sql .= " and $column in ($string) ";
    }

    public static function addStringEquals(&$sql, $column, $value)
    {
        if (empty($value)) {
            return;
        }
        $value = SqlMaker::sql_safe_replace($value);
        $sql .= " and $column='{$value}'";
    }

    public static function addEquals(&$sql, $column, $value)
    {
        if (empty($value)) {
            return;
        }
        $value = SqlMaker::sql_safe_replace($value);
        $sql .= " and $column={$value}";
    }

    public static function addFullLike(&$sql, $column, $value)
    {
        static::addFullLikes($sql, $column, $value);
    }

    public static function addFullLikes(&$sql, $columns, $value)
    {
        if (empty($columns)) {
            return;
        }
        if (empty($value)) {
            return;
        }
        $value = SqlMaker::sql_safe_replace($value);
        $columns = ArrayUtils::forceToArray($columns);
        $result = [];
        foreach ($columns as $column) {
            array_push($result, " $column like '%{$value}%'");
        }
        $sql .= " and (" . implode(" or ", $result) . ")";
    }

    public static function addLeftLike(&$sql, $column, $value)
    {
        if (empty($value)) {
            return;
        }
        $value = SqlMaker::sql_safe_replace($value);
        $sql .= " and $column like '{$value}%'";
    }

    public static function addRightLike(&$sql, $column, $value)
    {
        if (empty($value)) {
            return;
        }
        $value = SqlMaker::sql_safe_replace($value);
        $sql .= " and $column like '%{$value}'";
    }
}